<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>营销系统-优惠券编辑</title>
    <script src="../../../../static/js/vue.js" th:src="@{/js/vue.js}"></script>
	<link rel="stylesheet" href="../../../../static/css/element.css" th:href="@{/css/element.css}">
	<link rel="stylesheet" href="../../../../static/css/global.css" th:href="@{/css/global.css}" />
	<link rel="stylesheet" href="../../../../static/css/main.css" th:href="@{/css/main.css}" />
	<link rel="stylesheet" href="../../../../static/css/myelement.css" th:href="@{/css/myelement.css}" />
	<!-- 引入组件库 -->
	<script src="../../../../static/js/element.js" th:src="@{/js/element.js}"></script>
	<script src="../../../../static/js/jquery.min.js" th:src="@{/js/jquery.min.js}"></script>
	<script src="../../../../static/js/validate.expand.js" th:src="@{/js/validate.expand.js}"></script>
</head>
<body>
<div id="app">
    <div class="main-content" v-cloak>
    	<!-- 页面头部 -->
		<div class="page-header">
			<h1 class="page-title">优惠券编辑</h1>
			<div class="breadcrumb"><a href="javascript:top.location.reload();">首页</a><span>/</span>营销<span>/</span><a href="/vendor/promotion/coupon/tolist">优惠券列表</a></div>
		</div><!-- 页面头部 end -->
		
        <div class="main-content-body">
			<div class="edit-form">
				<el-form ref="coupon-form" :model="coupon" :rules="rules" label-width="100px">
                    <el-form-item prop="couponName" label="优惠券名称">
                        <el-input v-model="coupon.couponName" placeholder="请填入优惠券名称"></el-input>
                    </el-form-item>
                    <el-form-item prop="startValidTime" label="开始时间">
                        <el-date-picker
					      v-model="coupon.startValidTime"
					      type="datetime"
					      placeholder="选择生效的开始时间" value-format="yyyy-MM-dd hh:mm:ss">
					    </el-date-picker>
                    </el-form-item>
                    <el-form-item prop="endValidTime" label="结束时间">
                        <el-date-picker
					      v-model="coupon.endValidTime"
					      type="datetime"
					      placeholder="选择生效的结束时间" value-format="yyyy-MM-dd hh:mm:ss">
					    </el-date-picker>
                    </el-form-item>
                    <el-form-item prop="totalCount" label="发布总数">
                        <el-input v-model="coupon.totalCount" placeholder="优惠券发行的总数量"></el-input>
                    </el-form-item>
                    <el-form-item prop="couponPrice" label="面值">
                        <el-input v-model="coupon.couponPrice" placeholder="优惠券可抵扣的金额"></el-input>
                    </el-form-item>
                    <el-form-item prop="reachPrice" label="使用条件">
                        <el-input v-model="coupon.reachPrice" placeholder="满足多少元才能使用该券，填0或者不填表示没有条件限制"></el-input>
                    </el-form-item>
                    <el-form-item prop="limitCount" label="每人限领数量">
                        <el-input v-model="coupon.limitCount" placeholder="填0或者不填 表示可以无限领取"></el-input>
                    </el-form-item>
					<el-form-item prop="couponClient" label="适用终端">
						<el-radio-group v-model="couponClientType" @change="checkClientType">
							<el-radio v-for="o in couponClientTypeList" :key="o.key" :label="o.key">{{o.value}}</el-radio>
						</el-radio-group>

						<div v-if="couponClientType=='2'">
							<el-checkbox-group v-model="coupon.couponClient">
								<el-checkbox v-for="o in couponClientList" :label="o.key">{{o.value}}</el-checkbox>
							</el-checkbox-group>
						</div>
					</el-form-item>
					<el-form-item prop="obtainType" label="获取方式">
						<el-radio-group v-model="coupon.obtainType">
							<el-radio v-for="o in obtainTypeList" :key="o.value" :label="o.value">{{o.name}}</el-radio>
						</el-radio-group>
					</el-form-item>
					<el-form-item prop="state" label="启停">
						<el-radio-group v-model="coupon.state">
							<el-radio v-for="o in stateList" :key="o.key" :label="o.key">{{o.value}}</el-radio>
						</el-radio-group>
					</el-form-item>
					<el-form-item prop="couponType" label="优惠券类别">
						<el-radio-group v-model="coupon.couponType" @change="checkCouponType">
							<el-radio v-for="o in couponTypeList" :key="o.value" :label="o.value">{{o.name}}</el-radio>
						</el-radio-group>
					</el-form-item>

					<div v-show="coupon.couponType == 2">
						<div class="clearfix l_30 f_13">
							查看关联分类</span>
							<el-button class="ml_10" @click="openClassList">+ 关联分类</el-button>
						</div>
					</div>

					<div v-show="coupon.couponType == 3">
						<div class="clearfix l_30 f_13">
							请选择指定品牌</span>
							<el-button class="ml_10" @click="openBrandList">+ 选择品牌</el-button>
						</div>
						<div class="z-tables">
							<el-table :data="coupon.productList">
								<el-table-column label="序号" type="index"></el-table-column>
								<el-table-column label="品牌名称" prop="productName"></el-table-column>
								<el-table-column label="品牌英文名" prop="productNo"></el-table-column>
								<el-table-column label="操作">
									<template slot-scope="scope">
										<i class="el-icon-delete cur_pointer" @click="removeBrand(scope.row)"></i>
									</template>
								</el-table-column>
							</el-table>
						</div>
					</div>
                    
                    <div v-show="coupon.couponType == 4">
	                    <div class="clearfix l_30 f_13">
							请选择指定商品</span>
							<el-button class="ml_10" @click="openProductList">+ 选择商品</el-button>
						</div>
						<div class="z-tables">
							<el-table :data="coupon.productList">
								<el-table-column label="序号" type="index"></el-table-column>
			 					<el-table-column label="商品名称" prop="productName"></el-table-column>
							    <el-table-column label="商品编号" prop="productNo"></el-table-column>
							    <el-table-column label="商品SKU" prop="skuNo"></el-table-column>
							    <el-table-column label="操作">
									<template slot-scope="scope">
										<i class="el-icon-delete cur_pointer" @click="removeProduct(scope.row)"></i>
									</template>
							    </el-table-column>
							</el-table>
						</div>
					</div>

					<!-- 分类选择模态框 -->
					<el-dialog title="选择商品分类" :visible.sync="dialogClassVisible" width='500px'>
						<el-tree
								:data="showCategoryList"
								show-checkbox
								node-key="uuid"
								ref="categoryTree"
								:default-checked-keys="selectCategoryUuids"
								:default-expanded-keys="selectCategoryUuids"
								:props="categoryProps">
						</el-tree>
						<div slot="footer" class="dialog-footer">
							<el-button type="primary" @click="confirmCategory">提 交</el-button>
							<el-button @click="dialogClassVisible = false">关 闭</el-button>
						</div>
					</el-dialog>
					<!-- 分类选择模态框 end -->

					<!-- 选择品牌模态框 -->
					<el-dialog title="选择品牌" :visible.sync="brandDialogFormVisible" class="table-dialog" width="900px">
						<!--条件筛选-->
						<div class="content_item_filter clearfix">
							<div class="input-select fl btn-radid_none">
								<div class="filter-form filter-form-one clearfix">
									<el-input placeholder="品牌名称/品牌英文名" v-model="brandConditions['name#enName'].value" class="minW40 z_input-holder" ></el-input>
								</div>

								<div class="filter-operate">
									<el-tooltip class="item" content="查询" placement="bottom-start">
										<el-button icon="el-icon-search" @click="handleBrandQuery"></el-button>
									</el-tooltip>
									<el-tooltip class="item" content="清空" placement="bottom-start">
										<el-button icon="el-extend-clean" @click="handleBrandClear"></el-button>
									</el-tooltip>
								</div>
							</div>
						</div>

						<!--主体表格-->
						<div class="z-tables">
							<el-table :data="showBrandList" v-loading="listloading" style="width: 100%;" @selection-change="selsChange">
								<el-table-column type="selection" width="55"></el-table-column>
								<el-table-column label="品牌名称" prop="name"></el-table-column>
								<el-table-column label="品牌英文名" prop="enName"></el-table-column>
							</el-table>
						</div>

						<!--分页-->
						<div class="grid-content">
							<div class="bg-purple-light">
								<el-pagination
										@size-change="handleSizeChange"
										@current-change="handleCurrentChange"
										:current-page="currentPage"
										:page-sizes="pageSizeList"
										:page-size="pageSize"
										layout="total, sizes, prev, pager, next"
										:total="brandTotalNum">
								</el-pagination>
							</div>
						</div>

						<div slot="footer" class="dialog-footer">
							<el-button type="primary" @click="confirmBrand">提 交</el-button>
							<el-button @click="brandDialogFormVisible = false">关 闭</el-button>
						</div>
					</el-dialog>
					<!-- 选择品牌模态框 end -->
                    
                    <!-- 选择商品模态框 -->
					<el-dialog title="选择商品" :visible.sync="productDialogFormVisible" class="table-dialog" width="900px">
						<!--条件筛选-->
						<div class="content_item_filter clearfix">
			 				<div class="input-select fl btn-radid_none">
			 					<div class="filter-form filter-form-one clearfix">
				 					<el-input placeholder="商品名称/商品编号/商品Sku" v-model="productConditions['entityNo#productName#productSku']" class="minW40 z_input-holder" ></el-input>
								</div>

								<div class="filter-operate">
									<el-tooltip class="item" content="查询" placement="bottom-start">
								    	<el-button icon="el-icon-search" @click="handleProductQuery"></el-button>
								    </el-tooltip>
									<el-tooltip class="item" content="清空" placement="bottom-start">
								    	<el-button icon="el-extend-clean" @click="handleProductClear"></el-button>
								    </el-tooltip>
							    </div>
			 				</div>
						</div>
							
						<!--主体表格-->
						<div class="z-tables">
			 				<el-table :data="showProductList" v-loading="listloading" style="width: 100%;" @selection-change="selsChange">
			 					<el-table-column type="selection" width="55"></el-table-column>
			 					<el-table-column label="商品名称" prop="productName"></el-table-column>
							    <el-table-column label="商品编号" prop="productNo"></el-table-column>
							    <el-table-column label="商品SKU" prop="productSku"></el-table-column>
							    <el-table-column label="商品库存" prop="saleStock"></el-table-column>
							    <el-table-column label="订货价" prop="salesPrice"></el-table-column>
							</el-table>
			 			</div>
			 			
			 			<!--分页-->
			 			<div class="grid-content">
				 			<div class="bg-purple-light">
							    <el-pagination
		                            @size-change="handleSizeChange"
		                            @current-change="handleCurrentChange"
		                            :current-page="currentPage"
		                            :page-sizes="pageSizeList"
		                            :page-size="pageSize"
		                            layout="total, sizes, prev, pager, next"
		                            :total="totalNum">
		                    	</el-pagination>
						  	</div>
						</div>

						<div slot="footer" class="dialog-footer">
							<el-button type="primary" @click="confirmProduct">提 交</el-button>
							<el-button @click="productDialogFormVisible = false">关 闭</el-button>
						</div>
					</el-dialog>
			        <!-- 选择商品模态框 end -->
				        
                    <div class="edit-button-fixed">
	                    <div class="edit-button z-yuan-butn">
							<el-button type="primary" @click="savecoupon" :loading="loading">保存</el-button>
	            			<el-button @click="returnList">返回</el-button>
						</div>
					</div>
                </el-form>
             </div>
        </div>
   	</div>
</div>
</body>
<script th:inline="javascript">
	var app = new Vue({
        el: "#app",
        data: {
            oldCouponClient:'', //存放原始的couponClient
			oldCouponType:1,//存放原始couponType
			oldProductList:[],//存放原始coupon.productList
        	coupon: [[${dto}]],
            couponClientList:[[${couponClientList}]],
            obtainTypeList:[[${obtainTypeList}]],
            couponTypeList:[[${couponTypeList}]],
            stateList:[{key:true,value:"启用"},{key:false,value:"停用"}],
            couponClientType:'1',
            couponClientTypeList:[{key:'1',value:"全场通用"},{key:'2',value:"选择终端"}],
            loading:false,
            listloading:false,
            selectCategoryUuids:[[${selectCategoryUuids}]],//默认选中的分类uuids
            showCategoryList:[],
            categoryProps: {
                children: 'subCategoryList',
                label: 'categoryName'
            },
            showBrandList: [],
            showProductList: [],
            dialogClassVisible:false,
            brandDialogFormVisible:false,
            productDialogFormVisible: false,
            noBrandUuids:[[${noBrandUuids}]],
            brandConditions: {
                "name#enName": {
                    "operation": "ORLIKE",
                    "value": ""
                }
                /*"uuid": {
                    "operation": "NOTIN",
                    "value": []
                }*/
            },
            productConditions: {
            	"entityNo#productName#productSku": "",
            	"noSkuUuids": [[${noSkuUuids}]]
            },
            pageSizeList: [5, 10, 20, 50],
            brandTotalNum: 0,
            totalNum: 0,
            currentPage: 1, //当前页码数
            pageSize: 10,
            rules: {
            	couponName: [
                    {required: true, message: "请输入优惠券名称", trigger: 'blur'},
                    {max:40, message: '名称长度40个字符以内', trigger: 'blur'}
                ],
                couponPrice: [
                	{required: true, message: "请输入面值", trigger: 'blur'},
                	{validator: doubleDecimalValid, trigger: 'blur'}
                ],
                reachPrice: [
                	{validator: doubleDecimalValid, trigger: 'blur'}
                ],
                startValidTime: [
                	{required: true, message: "请选择开始时间", trigger: 'blur'},
                	{
                        validator: function (rule, value, callback) {
                            var endValidTime = app.coupon.endValidTime;
                            if (endValidTime != "" && value >= endValidTime) {
                                callback(new Error('开始时间应该小于结束时间'));
                            } else {
                                callback();
                            }
                        }, trigger: 'blur'
                    }
                ],
                endValidTime: [
                	{required: true, message: "请选择结束时间", trigger: 'blur'},
                	{
                        validator: function (rule, value, callback) {
                        	var startValidTime = app.coupon.startValidTime;
                            if (startValidTime != "" && value < startValidTime) {
                                callback(new Error('结束时间应该大于开始时间'))
                            } else {
                                callback();
                            }
                        }, trigger: 'blur'
                    }
                ],
                totalCount: [
                	{required: true, message: "请输入发布总数", trigger: 'blur'},
                	{validator: integerValid, trigger: 'blur'}
                ],
                limitCount: [
                	{validator: integerValid, trigger: 'blur'}
                ],
                couponClient: [
                	{required: true, message: "请选择适用终端", trigger: 'blur'}
                ],
                obtainType: [
	            	{required: true, message: "请选择获取方式", trigger: 'blur'}
	            ],
                state: [
                    {required: true, message: "请选择启停", trigger: 'blur'}
                ],
                couponType: [
	            	{required: true, message: "请选择优惠券类别", trigger: 'blur'}
	            ]
            }
        },
        mounted: function () {
            this.coupon.couponClient = this.coupon.couponClient.split(',');
            this.oldCouponClient = this.coupon.couponClient;
			if(this.coupon.couponClient=='1'){
                this.couponClientType = '1';
			}else{
                this.couponClientType = '2';
			}
			this.oldCouponType = this.coupon.couponType;
			this.oldProductList = this.coupon.productList;
			if(3==this.coupon.couponType){
                if(!this.brandConditions.uuid && this.noBrandUuids && this.noBrandUuids.length>0){
                    this.brandConditions.uuid = {
                        "operation": "NOTIN",
                        "value": this.noBrandUuids
                    }
                }
			}
        },
        methods: {
            checkClientType:function(){
                if("1"==app.couponClientType){
                    app.coupon.couponClient = ['1'];
                }else if("2"==app.couponClientType){
                    app.coupon.couponClient = this.oldCouponClient;
                }
            },
            checkCouponType:function(){
                app.coupon.productList = [];
                if(3==app.coupon.couponType){
                    if(!app.brandConditions.uuid && app.noBrandUuids && app.noBrandUuids.length>0){
                        app.brandConditions.uuid = {
                            "operation": "NOTIN",
                            "value": app.noBrandUuids
                        }
                    }
                }
                if(app.coupon.couponType==app.oldCouponType && app.coupon.couponType != 2){
                    app.coupon.productList = app.oldProductList;
				}
            },
            savecoupon: function () {
                let self = this;
                self.$refs['coupon-form'].validate((valid) => {
                    if (valid) {
                        if(self.coupon.couponType != 1 && self.coupon.productList.length <= 0){
                            var msg = '';
                            if(self.coupon.couponType == 2){
                                msg = '请至少关联一个分类';
                            }else if(self.coupon.couponType == 3){
                                msg = '请至少关联一个品牌';
                            }else if(self.coupon.couponType == 4){
                                msg = '请至少关联一个商品';
                            }
                            self.$message({
                                showClose: true,
                                duration: 1500,
                                message: msg,
                                type: 'error',
                                customClass: 'message-center'
                            });
                            return ;
                        }

                        app.coupon.couponClient = app.coupon.couponClient.join(',');
                    	self.loading = true;
                        $.ajax({
                            url: "/vendor/promotion/coupon/editCoupon",
                            type: "POST",
                            data: JSON.stringify(self.coupon),
                            contentType: "application/json;charset=UTF-8",
                            dataType: "json",
                            success: function (data) {
                                if (data && data.returnCode == "1") {
                                    self.$message({
                                    	showClose: true,
                                    	duration: 1500,
                                        message: '编辑优惠券成功',
                                        type: 'success',
                                        customClass: 'message-center',
                                        onClose: function () {
                                            window.location.href = "/vendor/promotion/coupon/tolist"
                                        }
                                    });
                                } else {
                                    self.$message({
                                    	showClose: true,
                                    	duration: 1500,
                                        message: '编辑优惠券失败',
                                        type: 'error',
                                        customClass: 'message-center'
                                    });
                                    self.loading = false;
                                }
                            },
                            error: function () {
                                self.$message({
                                	showClose: true,
                                	duration: 1500,
                                    message: '系统异常，请联系管理员',
                                    type: 'error',
                                    customClass: 'message-center'
                                });
                                self.loading = false;
                            }
                        });
                    }
                });
            },
            returnList: function () {
            	window.location.href = "/vendor/promotion/coupon/tolist";
            },
            openClassList:function(){
                this.dialogClassVisible = true;
                queryClassList(this);
            },
            openBrandList: function() {
                this.brandDialogFormVisible = true;
                queryBrandList(this);
            },
            openProductList: function() {
            	this.productDialogFormVisible = true;
            	queryProductList(this);
            },
            handleBrandQuery(){
                this.currentPage = 1;
                var that = this;
                queryBrandList(that);
            },
            handleProductQuery() {
                this.currentPage = 1;
                var that = this;
                queryProductList(that);
            },
            handleBrandClear(){
                this.brandConditions['name#enName'].value = "";
            },
            handleProductClear() {
                this.productConditions['entityNo#productName#productSku'] = "";
            },
            selsChange(sels) {  
                this.sels = sels;
            },
            handleSizeChange: function (val) {
		  		this.pageSize = val;
		  		var that = this;
		  		queryProductList(that);
		    },
		    handleCurrentChange: function (val) {
		    	 this.currentPage = val;
		    	 var that = this;
		    	 queryProductList(that);
		    },
            removeBrand(item){
                var self = this;
                self.coupon.productList.splice(self.coupon.productList.indexOf(item),1);
                self.brandConditions.uuid.value.splice(self.brandConditions.uuid.value.indexOf(item),1);
                if(self.brandConditions.uuid.value.length==0){
                    self.brandConditions.uuid = undefined;
                }
            },
		    removeProduct(item) {
		    	var self = this;
		    	self.coupon.productList.splice(self.coupon.productList.indexOf(item),1);
		    	self.productConditions.noSkuUuids = self.productConditions.noSkuUuids.replace(item.uuid+",","").replace(","+item.uuid,"").replace(item.uuid,"");
		    },
            confirmCategory:function(){
                var self = this;
                //获取最后一级的分类数组
                var selectCategoryList = this.$refs.categoryTree.getCheckedNodes(true,false);
                var selectCategoryUuids = this.$refs.categoryTree.getCheckedKeys(true);
                if(!selectCategoryList || selectCategoryList.length==0){
                    self.$message({
                        duration: 2000,
                        message: '请至少选择一个分类',
                        type: 'warning',
                        customClass: 'message-center'
                    });
                    return ;
                }
                self.selectCategoryUuids = selectCategoryUuids;
                for(var i in selectCategoryList){
                    var category = {};
                    category.relUuid = selectCategoryList[i].uuid;
                    category.productName = selectCategoryList[i].categoryName;
                    self.coupon.productList.push(category);
                }
                self.dialogClassVisible = false;
            },
            confirmBrand:function (val) {
                var self = this;
                var brandUuids = [];
                if(self.sels){
                    for(var i in self.sels){
                        brandUuids.push(self.sels[i].uuid);
                    }
                }
                if(brandUuids.length==0){
                    self.$message({
                        duration: 2000,
                        message: '请至少选择一个品牌',
                        type: 'warning',
                        customClass: 'message-center'
                    });
                    return ;
                }

                if(!self.brandConditions.uuid){
                    self.brandConditions.uuid = {
                        "operation": "NOTIN",
                        "value": []
                    }
                }
                if(self.brandConditions.uuid.value.length==0){
                    self.brandConditions.uuid.value = brandUuids;
                }else{
                    self.brandConditions.uuid.value = self.brandConditions.uuid.value.concat(brandUuids);
                }
                for(var i in self.sels){
                    var brand = {};
                    brand.relUuid = self.sels[i].uuid;
                    brand.productName = self.sels[i].name;
                    brand.productNo = self.sels[i].enName;
                    self.coupon.productList.push(brand);
                }
                self.brandDialogFormVisible = false;
            },
		    confirmProduct:function (val) {
		    	var self = this;
				var skuUuids = "";
				if(self.sels){
					skuUuids = self.sels.map(item => item.uuid).join();
				}
				if(skuUuids == ""){
					self.$message({
                    	duration: 2000,
                        message: '请至少选择一个商品',
                        type: 'warning',
                        customClass: 'message-center'
                    });
					return ;
				}
				if(self.productConditions.noSkuUuids === ""){
					self.productConditions.noSkuUuids = skuUuids;
				}else{
					self.productConditions.noSkuUuids = self.productConditions.noSkuUuids + "," + skuUuids;
				}
				for(var i in self.sels){
                    var product = {};
                    product.relUuid = self.sels[i].productUuid;
                    product.productName = self.sels[i].productName;
                    product.productNo = self.sels[i].productNo;
                    product.skuNo = self.sels[i].productSku;
                    product.skuUuid = self.sels[i].uuid;
                    self.coupon.productList.push(product);
				}
				self.productDialogFormVisible = false;
		    }
        }
    });

    function queryClassList(app) {

        $.ajax({
            url: "/vendor/product/product/getAllCategoryTree",
            type: "POST",
            data: null,
            contentType: "application/json;charset=UTF-8",
            dataType: "json",
            success: function (data) {
                if (data && data.returnCode == "1") {
                    app.showCategoryList = data.returnMessage;
                }
            }
        });
    }

    function queryBrandList(app) {
        app.listloading = true;

        let queryMessage = {
            "queryPage": app.currentPage,
            "pageShow": app.pageSize,
            "queryParams": app.brandConditions,
            "sortMap": {
                "createTime": "desc"
            }
        };
        $.ajax({
            url: "/vendor/product/productbrand/listByIndustry",
            type: "POST",
            data: JSON.stringify(queryMessage),
            contentType: "application/json;charset=UTF-8",
            dataType: "json",
            success: function (data) {
                if (data && data.returnCode == "1") {
                    app.showBrandList = data.returnMessage;
                    app.brandTotalNum = data.pager.totalNum;
                }
                app.listloading = false;
            }
        });
    }
    
    function queryProductList(app) {
    	app.listloading = true;
        let queryMessage = {
            "queryPage": app.currentPage,
            "pageShow": app.pageSize,
            "simpleQueryParams": app.productConditions,
            "sortMap": {
                "createTime": "desc"
            }
        };
        $.ajax({
            url: "/vendor/stock/stock/productSkuList",
            type: "POST",
            data: JSON.stringify(queryMessage),
            contentType: "application/json;charset=UTF-8",
            dataType: "json",
            success: function (data) {
                if (data && data.returnCode == "1") {
                    app.showProductList = data.returnMessage;
                    app.totalNum = data.pager.totalNum;
                }
                app.listloading = false;
            }
        });
    }
</script>
</html>
